package cn.tjad.tjad2.module.form.views;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.View;
import android.widget.TextView;

import cn.tjad.tjad2.consts.Keys;
import cn.tjad.tjad2.data.bean.Document;
import cn.tjad.tjad2.data.bean.FileBean;
import cn.tjad.tjad2.data.bean.FormDetail;
import cn.tjad.tjad2.route.PageId;
import cn.tjad.tjad2.utils.RouteUtils;

public class ViewPortView extends FormBaseLayout implements View.OnClickListener {

    private TextView textView;
    private Document selectedDocument;

    public ViewPortView(Context context) {
        super(context);
    }

    public ViewPortView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    protected void init() {
        super.init();
        addBodyView();
        setOnClickListener(this);
    }

    private void addBodyView() {
        textView = new TextView(getContext());
        textView.setText("新增视口");
        textView.setTextSize(14);
        textView.setGravity(Gravity.CENTER);
        this.addView(textView);
    }

    @Override
    public void setEnabled(boolean enabled) {
        super.setEnabled(enabled);
        if (enabled) {
            setOnClickListener(this);
        } else {
            setOnClickListener(null);
        }
    }

    @Override
    public void setFormStepDetail(FormDetail.FormStepDetail formStepDetail) {
        super.setFormStepDetail(formStepDetail);
        showDocumentName(formStepDetail.document);
    }

    private void showDocumentName(Document document) {
        if (document != null) {
            textView.setText(document.name);
        } else {
            textView.setText("新增视口");
        }
    }

    @Override
    public void onClick(View v) {
        Bundle bundle = new Bundle();
        bundle.putString(Keys.SUFFIX, "rvt");
        RouteUtils.toPageForResult((Activity) getContext(), PageId.FILE_SELECT, bundle, 1001);
    }

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == 1001 && resultCode == Activity.RESULT_OK) {
            FileBean selectFile = (FileBean) data.getSerializableExtra(Keys.FILE);
            if (selectFile != null && selectFile.document != null) {
                this.selectedDocument = selectFile.document;
                showDocumentName(this.selectedDocument);
                formStepDetail.value = String.valueOf(this.selectedDocument.id);
            }
        }
    }
}
